from selenium.webdriver.support.wait import WebDriverWait


class BaseAction:

    def __init__(self, driver):
        self.driver = driver

    def find_element(self, feature, time=10, poll=0.1):
        return WebDriverWait(self.driver, time, poll).until(lambda x: x.find_element(*feature))

    def find_elements(self, feature, time=10, poll=0.1):
        return WebDriverWait(self.driver, time, poll).until(lambda x: x.find_elements(*feature))

    def click(self, feature, time=10, poll=0.1):
        self.find_element(feature, time, poll).click()

    def send_keys(self, feature, text, time=10, poll=0.1):
        self.find_element(feature, time, poll).send_keys(text)

    def get_text(self, feature, time=10, poll=0.1):
        return self.find_element(feature, time, poll).text

    def get_alert(self):
        return self.driver.switch_to.alert

    def clear(self, feature, time=10, poll=0.1):
        self.find_element(feature, time, poll).clear()

    def get_attribute(self, feature, name, time=10, poll=0.1):
        return self.find_element(feature, time, poll).get_attribute(name)

    def switch_to_window_by_index(self, index=-1):
        """
        根据索引切换到对应的窗口
        :param index: 窗口索引，从 0 开始
        """
        windows = self.driver.window_handles
        if index < len(windows):
            self.driver.switch_to.window(windows[index])
        else:
            raise IndexError(f"窗口索引 {index} 超出范围，当前窗口数量: {len(windows)}")
